<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
const router = useRouter();
// 跳转页面
const jumpTo = (path) => {
  router.push(path);
};

const productList = ref([]);
const getProductList = async () => {
  try {
    const res = await axios.get(`${apiUrl}/cart/list?page=1&limit=100&status=1`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      productList.value = res.data.data.valid;
      productList.value.forEach((item) => {
        item.selected = true;
        selectAll.value = true;
      });
    }
  } catch (e) {}
};

// 全选
const selectAll = ref(false);

// 修改选择
const changeSelect = () => {
  let allIsSelect = true;
  productList.value.forEach((item) => {
    if (item.selected === false) {
      allIsSelect = false;
    }
  });

  selectAll.value = allIsSelect;
  getTotal();
};

// 批量删除商品
const delAll = (isAll) => {
  let ids = [];

  productList.value.forEach((item) => {
    if (isAll) {
      // 如果是删除全部
      ids.push(item.id);
    } else {
      if (item.selected === true) {
        // 如果是删除选中的
        ids.push(item.id);
      }
    }
  });
  deleteProduct(ids);
};

const total = ref({});
const getTotal = async () => {
  try {
    const res = await axios.get(`${apiUrl}/cart/count?numType=0`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      total.value = res.data.data;
    }
  } catch (e) {}
};

const deleteProduct = async (ids) => {
  try {
    const res = await axios.post(
      `${apiUrl}/cart/del`,
      { ids },
      {
        headers: {
          "Authori-zation": `Bearer ${getToken()}`,
        },
      }
    );

    getProductList();
  } catch (e) {}
};

const deleteAll = () => {
  const ids = productList.value.map((item) => item.id);
  deleteProduct(ids);
};

const deleteSellected = () => {
  const ids = productList.value.filter((item) => item.selected).map((item) => item.id);
  deleteProduct(ids);
};

const changeProductNum = async (product) => {
  try {
    const res = await axios.post(
      `${apiUrl}/cart/num`,
      { id: product.id, number: product.cart_num },
      {
        headers: {
          "Authori-zation": `Bearer ${getToken()}`,
        },
      }
    );
    if (res.data.status !== 200) {
      ElMessage({
        message: res.data.msg,
        type: "warning",
      });
    }
    getProductList();
    getTotal();
  } catch (e) {}
};

const handleselectAll = async () => {
  if (selectAll.value) {
    productList.value.forEach((item) => (item.selected = true));
  } else {
    productList.value.forEach((item) => (item.selected = false));
  }
};

const buyNow = () => {
  const seletecdProduct = productList.value.filter((item) => item.selected);
  const ids = seletecdProduct.map((item) => item.id);
  jumpTo("/order?cartId=" + ids.join(",") + "&new=0");
};

const getTotalPrice = () => {
  const seletecdProduct = productList.value.filter((item) => item.selected);
  let total = 0;
  seletecdProduct.forEach((item) => {
    total += item.truePrice * item.cart_num;
  });
  return total.toFixed(2);
};

onMounted(() => {
  getTotal();
  getProductList();
});
</script>

<template>
  <div class="middle">
    <el-checkbox
      v-model="selectAll"
      :label="$t('car.all')"
      size="large"
      @change="handleselectAll"
    />
    <div class="productList" v-if="productList.length > 0">
      <div class="item" v-for="item in productList" :key="item.id">
        <div class="cItem">
          <el-checkbox v-model="item.selected" @change="changeSelect" size="large" />
        </div>
        <div
          class="cItem w40 nameBox cur"
          @click="jumpTo('/productDetail?id=' + item.product_id)"
        >
          <div class="coverUrl">
            <img :src="item.productInfo.image" alt="" />
          </div>
          <div class="name">
            {{ item.productInfo.store_name }}<br /><el-text class="mx-1" type="info">{{
              item.productInfo.attrInfo.suk
            }}</el-text>
          </div>
        </div>
        <div class="cItem w20 center">
          <div class="color">{{ item.color }}</div>
          <div class="specification">{{ item.specification }}</div>
        </div>
        <div class="cItem center priceBox">
          <div class="price">￥{{ item.truePrice }}</div>
          <div class="rate" v-if="item.rate > 0">
            {{ $t("car.promotion") }}{{ item.rate }}%
          </div>
        </div>
        <div class="cItem center">
          <el-input-number
            class="numBox"
            v-model="item.cart_num"
            @change="changeProductNum(item)"
            :min="1"
          />
        </div>
        <div class="cItem center">
          <div class="delBox" @click="deleteProduct([item.id])">
            <el-icon><Delete /></el-icon>
            <span>{{ $t("car.del") }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="noData" v-else>
      <el-empty :description="$t('car.nodata')">
        <el-button type="primary" @click="jumpTo('/productList')">{{
          $t("car.add")
        }}</el-button>
      </el-empty>
    </div>
  </div>

  <div class="feedback">
    <div class="middle">
      <div class="leftBox">
        <div class="item" @click="deleteSellected()">
          <el-icon><Delete /></el-icon>
          <span>{{ $t("car.delSel") }}</span>
        </div>
        <div class="item" @click="deleteAll(true)">
          <el-icon><Delete /></el-icon>
          <span>{{ $t("car.delAll") }}</span>
        </div>
      </div>
      <div class="rightBox">
        <div class="item">
          {{ $t("car.selected") }}{{ total.count }}{{ $t("car.selectedEnd") }}
        </div>
        <div class="totalPrice item">
          {{ $t("car.total") }}
          <span class="price">￥{{ getTotalPrice() }}</span>
        </div>

        <div class="item">
          <el-button type="primary" @click="buyNow">{{ $t("car.settle") }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.middle {
  padding: 20px 0;
}
.topMenu {
  margin-top: 30px;
}

.searchBox {
  display: flex;
  margin-top: 15px;

  .label {
    line-height: 30px;
    margin-right: 20px;
  }
}

::v-deep .el-input__wrapper {
  border-radius: 0;
}

.feedback {
  background-color: #f6f6f6;
  // position: fixed;
  // bottom: 0;
  // left: 0;
  width: 100%;
  // z-index: 10;

  .middle {
    display: flex;
    justify-content: space-between;

    .title {
      font-size: 16px;
      font-weight: bold;
      margin-top: 40px;
      margin-bottom: 20px;
    }

    .leftBox {
      width: 500px;
      position: relative;
      padding-right: 100px;
      display: flex;
      line-height: 30px;

      .el-icon {
        position: relative;
        top: 3px;
        margin-right: 5px;
      }

      .feedbackImgBox {
        width: 100%;
        margin-top: 30px;
        margin-bottom: 60px;
        img {
          width: 100%;
        }
      }

      .desc {
        color: #666;
        font-size: 12px;
      }

      .item {
        margin-right: 30px;
        cursor: pointer;
        color: #444;
      }
    }

    .rightBox {
      width: 50%;
      padding-left: 100px;
      display: flex;
      justify-content: end;

      .item {
        margin-left: 40px;
        line-height: 30px;
        color: #666;

        .price {
          color: #000;
          font-size: 18px;
        }
      }

      .title {
        margin-top: 70px;
      }
    }
  }
}

.inputBox {
  display: flex;

  .left {
    margin-right: 30px;
  }
}

::v-deep .el-checkbox__label {
  width: calc(1400px - 50px);
  display: flex;
  padding-left: 30px;
}

::v-deep .bottomInput .el-input__wrapper {
  background-color: rgba(0, 0, 0, 0);
  box-shadow: none;
  border-bottom: 1px solid #dcdcdc;
  margin-bottom: 10px;
}

.productList {
  min-height: calc(100vh - 251px);
  .item {
    padding: 20px 0;
    box-sizing: border-box;
    height: 140px;
    width: 100%;
    display: flex;
    border-bottom: 1px solid #f3f3f3;
  }
}

.cItem {
  color: #666;
  &:first-child {
    width: 50px !important;
    line-height: 105px;
  }
  width: 25%;

  &.w40 {
    width: 40%;
  }
  &.w20 {
    width: 20%;
  }

  .name {
    width: 300px;
    white-space: normal;
    font-weight: bold;
    line-height: 20px;
    padding-top: 30px;
    color: #000;
  }

  &.center {
    text-align: center;
  }

  .coverUrl {
    width: 100px;
    height: 100px;

    img {
      width: 100%;
      height: 100%;
    }
  }

  &.nameBox {
    display: flex;
  }

  .color {
    margin-top: 20px;
    margin-bottom: 10px;
  }

  &.priceBox {
    display: flex;
    box-sizing: border-box;

    .price {
      color: #000;
      margin-right: 15px;
      margin-top: 30px;
      font-size: 16px;
    }

    .rate {
      padding: 5px 10px;
      background-color: rgb(41, 97, 152);
      color: #fff;
      box-sizing: border-box;
      height: 32px;
      margin-top: 24px;
    }
  }
}

.numBox {
  margin-top: 20px;
}

.delBox {
  margin-top: 26px;
  cursor: pointer;
  span {
    margin-left: 15px;
  }
}
</style>
